//
//  SignUpViewController.m
//  PokerHandUp
//
//  Created by psvn047 on 6/8/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SignInViewController.h"
#import "SignUpViewController.h"
#import "AppDelegate.h"
#import "AccountService.h"
#import "ValidateUtils.h"
@implementation SignUpViewController
NSString * RECAPTCHA_PRIVATE_KEY = @"6Lc0P84SAAAAACC04acvT0xWtJM2uBA2dRMarWvA";

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
    [wvCaptcha release];
    [tfEmail release];
    [tfFullName release];
    [tfPassword release];
    [tfReCaptcha release];
    [self registerKeyboardNotification];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // init recaptcha
    NSString* string = [[NSBundle mainBundle] pathForResource:@"recaptchar" ofType:@"html"];
    NSURL* url = [[NSURL alloc] initFileURLWithPath:string]; 
    wvCaptcha.backgroundColor = [UIColor clearColor];
    wvCaptcha.opaque = NO;
    wvCaptcha.delegate = self;
    wvCaptcha.userInteractionEnabled = YES;
    [[[wvCaptcha subviews] lastObject] setScrollEnabled:NO];
    [wvCaptcha loadRequest:[NSURLRequest requestWithURL:url]];
    
    // lock icon
    tfPassword.secureTextEntry = YES;
    
    
    
    tfFullName.text = NSLocalizedString(@"signup.text.fullname", @"");
    tfEmail.text = NSLocalizedString(@"signup.text.email", @"");
    tfPassword.text = NSLocalizedString(@"signup.text.password", @"");
    tfReCaptcha.text = NSLocalizedString(@"signup.text.recaptcha", @"");
    
    [self registerKeyboardNotification];
    
    UIScrollView* scrollview = (UIScrollView *) self.view ;
    scrollview.scrollEnabled = YES;
    scrollview.contentSize = CGSizeMake(320, 200);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)cancelAction:(id)sender
{
    [[AppDelegate sharedController] showWelcomeScreen];
}
- (IBAction)signUpAction:(id)sender
{
    reCaptchaResponse = [wvCaptcha stringByEvaluatingJavaScriptFromString:@"getText()"];
    //[wvCaptcha reload];
    BOOL validate = true;
    if(![ValidateUtils validateEmail:tfEmail.text] )
    {
        validate = false;
    }
    if(![ValidateUtils validateFullName:tfFullName.text])
    {
        validate = false;
    }
    if(validate)
    {
        // Test service
        AccountService* service = [[AccountService alloc] init];
        service.serviceCallbackDelegate = self;
        [service signUp:@"SignUp" fullName:tfFullName.text emailAddress:tfEmail.text password:tfPassword.text recaptchaPrivateKey:RECAPTCHA_PRIVATE_KEY recaptchaChallenge:tfReCaptcha.text recaptchaResponse:reCaptchaResponse];
    }
    else
    {
        [self showAlert: @"Alert" message: @"Please input data"];
    }

}

// Edit funtion
- (void)registerKeyboardNotification 
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification 
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification 
                                               object:nil];
}

- (void)unregisterKeyboardNotification 
{
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardDidShowNotification 
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardDidHideNotification 
                                                  object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification 
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize;
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_3_1
    kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
#else 
    kbSize = [[info objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
#endif
    UIScrollView *scrollView = (UIScrollView*)self.view;
    CGPoint scrollPoint;
    int tmp = tfActive.frame.origin.y - 78;
    if(tmp >= 0)
    {
        scrollPoint = CGPointMake(0, tmp);
    }
    else {
        scrollPoint = CGPointMake(0,0);
    }
   
    contentOffset = scrollView.contentOffset;
    [scrollView setContentOffset:scrollPoint animated:YES];
    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, scrollView.contentSize.height + kbSize.height);
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification 
{
    NSDictionary* info = [aNotification userInfo];
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_3_1
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
#else 
    CGSize kbSize = [[info objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
#endif
    UIScrollView *scrollView = (UIScrollView*)self.view;
    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, scrollView.contentSize.height - kbSize.height);
    [scrollView setContentOffset:contentOffset animated:YES];
    scrollView.contentOffset = CGPointZero;
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
    NSString* trimStr = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([trimStr compare: @""] == NSOrderedSame)
    {
        if(textField == tfFullName)
        {
            textField.text = NSLocalizedString(@"signup.text.fullname", @"");
        }
        else if(textField == tfEmail)
        {
            textField.text = NSLocalizedString(@"signup.text.email", @"");
        }
        else if(textField == tfPassword)
        {
            textField.text = NSLocalizedString(@"signup.text.password", @"");
        }
        else if(textField == tfReCaptcha)
        {
            textField.text = NSLocalizedString(@"signup.text.recaptcha", @"");
        }
    }
    
    // 
     [tfActive resignFirstResponder];
    tfActive = NULL;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    tfActive = textField;
    if(tfActive == tfFullName)
    {
        if([tfActive.text compare:NSLocalizedString(@"signup.text.fullname", @"")] == NSOrderedSame)
        {
            tfActive.text = @"";
        }
    }
    else if(tfActive == tfEmail)
    {
        if([tfActive.text compare:NSLocalizedString(@"signup.text.email", @"")] == NSOrderedSame)
        {
            tfActive.text = @"";
        }
    }
    else if(tfActive == tfPassword)
    {
        if([tfActive.text compare:NSLocalizedString(@"signup.text.password", @"")] == NSOrderedSame)
        {
            tfActive.text = @"";
        }
    }
    else if(tfActive == tfReCaptcha)
    {
        if([tfActive.text compare:NSLocalizedString(@"signup.text.recaptcha", @"")] == NSOrderedSame)
        {
            tfActive.text = @"";
        }
    }
}

#pragma mark - ServiceCallbackDelegate
- (void)successedCallback:(NSString*) serviceId reponseData:(NSObject*) data
{
    NSDictionary* json = (NSDictionary*) data;
    if(json != NULL)
    {
        [[AppDelegate sharedController] showSignInScreen];
    }
    else
    {
        NSLog(@"Empty data");
        [self showAlert:@"Alert" message:@"Reponse data is empty"];
    }
}
- (void)failedCallback:(NSString*) serviceId reponseData:(NSObject*) data
{
    NSLog(@"failedCallback");
    NSDictionary* json = (NSDictionary*) data;
    [self showAlert:@"Alert" message:[json objectForKey:@"message"]];
}

-(void) showAlert:(NSString*) title message: (NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
@end
